package com.umakr.ax.utils;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.Version;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

/**
 *
 * @author sc
 * @date 2018/1/26
 */
public class FreeMarkerUtil {
    private String baseDir;
    protected static final Log logger = LogFactory.getLog(FreeMarkerUtil.class);
    public FreeMarkerUtil(String baseDir){
        this.baseDir = baseDir;
    }

    public void make(Object root,String ftlName, String descPath){

        FileWriter out = null;
        try {
            descPath = baseDir+File.separator+descPath;
            File file = new File(descPath);
            if(!file.isDirectory()){
                file.mkdirs();
            }

            File outFile = new File(descPath+File.separator+"index.html");

            //通过一个文件输出流，就可以写到相应的文件中
            out = new FileWriter(outFile);
            Template temp = getTemplate(ftlName);
            temp.process(root, out);
        } catch (IOException e) {
            logger.error(e);
        } catch (TemplateException e) {
            e.printStackTrace();
        } finally {
            try {
                if(out!=null) {
                    out.close();
                }
            } catch (IOException e) {
                logger.error(e);
            }
        }
    }

    /**
     * 获取模板
     * @param name
     * @return
     */
    private Template getTemplate(String name) {
        try {
            //通过Freemaker的Configuration读取相应的ftl
            Configuration cfg = new Configuration(new Version("2.3.23"));
            //设定去哪里读取相应的ftl模板文件
            cfg.setClassForTemplateLoading(getClass(),"/tpl");
            //在模板文件目录中找到名称为name的文件
            Template temp = cfg.getTemplate(name);
            return temp;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }


}
